import 'dart:async';
import 'package:cbec_app/pages/my/controller/safe_account_ctr.dart';
import 'package:cbec_app/utils/AppData.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import '../../../components/base/base_ctr.dart';
import '../../../components/http/network.dart';

class SettingPayPasswordCtr extends BaseController {
  /*手机号*/
  String phoneNumber = AppData.phoneNumber ?? '';

  /*支付密码*/
  String payPassWord = '';

  /*验证码*/
  String msgCode = '';

  bool isOpenEye = false;

  TextEditingController payPassWordController = TextEditingController();

  TextEditingController msgCodeController = TextEditingController();

  bool isCountingDown = false; // 用于表示是否正在倒计时

  int countdown = 60; // 倒计时时间，单位秒

  Timer? countdownTimer;

  /// 获取验证码
  void fetchVerifyCode() {
    if (isCountingDown) return; // 如果正在倒计时，直接返回
    // 发送请求获取验证码
    Network.getMsgCode(phoneNumber, 'edit_pay_password').then((onValue) {
      // 在网络请求成功后启动倒计时
      if (onValue) {
        isCountingDown = true; // 开始倒计时
        startCountdown();
      } else {
        // 处理验证码请求失败的逻辑（例如提示错误）
        isCountingDown = false;
        update();
      }
    }).catchError((error) {
      // 请求失败的处理
      isCountingDown = false;
      update();
    });
  }

  // 开始倒计时
  void startCountdown() {
    countdown = 60; // 重置倒计时
    update();
    countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (countdown > 0) {
        countdown--;
      } else {
        stopCountdown();
      }
      update();
    });
  }

  // 停止倒计时
  void stopCountdown() {
    if (countdownTimer != null) {
      countdownTimer?.cancel();
    }
    isCountingDown = false;
    update();
  }

  /// 提交
  void submit() {
    Network.editPassword(payPassWord, payPassWord, 1).then((value) {
      if (value) {
        Get.back();
        Get.find<SafeAccountCtr>().hasPayPassword();
      }
    });
  }

  /// 更新密码的方法（例如，当输入框改变时调用）
  void updatePayPassWord(String newPassWord) {
    if (newPassWord.length > 6) {
      payPassWord = newPassWord.substring(0, 6);
      Tools.showToast('支付密码限制6位');
    } else {
      payPassWord = newPassWord;
    }
    payPassWordController.text = payPassWord;
    update();
  }

  void toggleEye() {
    isOpenEye = !isOpenEye;
    update();
  }

  /// 验证码
  void updateMsgCode(String code) {
    if (code.length > 6) {
      Tools.showToast('验证码不超过6位');
    }
    msgCode = code;
    msgCodeController.text = msgCode;
    update();
  }

  @override
  void onClose() {
    if (countdownTimer != null) {
      countdownTimer!.cancel();
    }
    super.onClose();
  }
}
